let that = null;
let mine = require("../../../api/mine.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: {},//用户信息
    bindtap: 'login',//头像是否可以按
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
  },

  /**
    * 生命周期函数--监听页面显示
    */
  onShow: function () {
    let user = wx.getStorageSync('user')
    // 判断是否有缓存
    if (user != '') {
      that.setData({
        user: user,
        bindtap: 'logout'
      })
    } else {
      that.setData({
        user: user,
        bindtap: 'login'
      })
    }
  },

  /*
  **登录**
  */
  async login() {
    that.setData({
      bindtap: 'logout'
    })
    await wx.getUserProfile({
      desc: '作为维修用户信息使用',
      async success(res) {
        wx.showLoading({
          title: '加载中...',
          mask: true,
        })
        const login = await mine.login().then(res => { return res; });
        wx.hideLoading({
          success: (res) => { console.log('数据加载完成') },
        })
        //用户是否存在
        if (login.login == 0) {
          wx.setStorageSync('user', res.userInfo)
          wx.navigateTo({
            url: '../Info/Info?to=/miniprogram/pages/mine/home/home',
          })
        } else {
          wx.setStorageSync('user', login.data)
          await that.setData({
            user: {
              avatarUrl: login.data.avatarUrl,
              nickName: login.data.nickName
            }
          })
        }
        console.log('微信登陆成功！')
      },
      fail: (res) => {
        console.log('登录失败！');
        that.setData({
          bindtap: 'login',
        })
      }
    })
  },

  /**
   * 退出登录 
   */
  async logout() {
    // 清除缓存
    await wx.removeStorageSync('user');

    // 修改页面数据
    that.setData({
      user: {},
      bindtap: 'login',
    })
  },

  /**
   * 跳转功能页面
   */
  ToLink(e) {
    let link = e.currentTarget.dataset.link;
    // 是否跳转到用户信息
    if (link == '../Info/Info') {
      let user = wx.getStorageSync('user')
      // 是否登录
      if (user == '') {
        console.log('Not login, Please login')
        wx.navigateTo({
          url: '../login/login?to=/miniprogram/pages/mine/Info/Info',
        })
      } else {
        wx.navigateTo({
          url: link + "?to=/miniprogram/pages/mine/Info/Info",
        })
      }
    } else {
      wx.navigateTo({
        url: link,
      })
    }
  },

  
    /**
     * 右上角分享
     */
    onShareAppMessage() {
      return {
          title: '首页',
          path: '/pages/CA/home/home',
          imageUrl: '../../../images/share.png'
      }
  },
})